package com.mondo.financialwallet.presentation.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.example.common.ui.BaseActivity;
import com.mondo.financialwallet.R;
import com.mondo.financialwallet.data.DataRepository;
import com.mondo.financialwallet.presentation.model.HotProducts;
import com.mondo.financialwallet.presentation.event.RequestHoldProductEvent;
import com.mondo.financialwallet.presentation.event.RequestUserAssetEvent;
import com.mondo.financialwallet.presentation.event.RequestWalletAssetEvent;
import com.mondo.financialwallet.presentation.ui.dialog.VerificationPasswordDialog;
import com.mondo.financialwallet.presentation.utils.ActivityTitleBarHelper;
import com.mondo.financialwallet.presentation.utils.AndroidUtils;
import com.mondo.financialwallet.presentation.utils.DateUtils;
import com.mondo.financialwallet.presentation.utils.LocalConfigStorage;
import com.mondo.financialwallet.presentation.utils.Toasts;

import org.greenrobot.eventbus.EventBus;

import butterknife.Bind;

/**
 * 购买产品
 *
 * TODO 有中文符号
 */
public class PurchaseProductActivity extends BaseActivity {

    private static final String EXTRA_PRODUCT = "PRODUCT";

    public static void launch(Context context, HotProducts product) {
        context.startActivity(new Intent(context, PurchaseProductActivity.class)
                .putExtra(EXTRA_PRODUCT, product));
    }

    @Bind(R.id.all_text_view) TextView mAllTextView;
    @Bind(R.id.purchase_view) Button mPurchaseView;
    @Bind(R.id.name_text_view) TextView mNameTextView;
    @Bind(R.id.minimum_day_text) TextView mMinimumDayText;
    @Bind(R.id.protocol_privacy_view) View mProtocolPrivacyView;
    @Bind(R.id.text_percentage_assets) TextView mPercentageAssets;
    @Bind(R.id.purchase_product_tips_text) TextView mPurchaseProductTipsText;
    @Bind(R.id.available_assets_text) TextView mAvailableAssetsText;
    @Bind(R.id.purchase_product_amount_edit) EditText mPurchaseProductAmountEdit;
    @Bind(R.id.protocol_selected_box) CheckBox mProtocolSelectedBox;

    private HotProducts mProduct;

    @Override
    protected int getLayoutID() {
        return R.layout.activity_purchase_product;
    }

    @Override
    protected void initActions() {
        ActivityTitleBarHelper.init(this, R.string.title_purchase_product);

        // 商品
        mProduct = (HotProducts) getIntent().getSerializableExtra(EXTRA_PRODUCT);

        // 产品信息
        mNameTextView.setText(mProduct.getTitle());          // 产品名称
        mMinimumDayText.setText("投资期限：" + mProduct.getMinimumDay() + "天");    // 期限
        mPurchaseProductTipsText.setText(Html.fromHtml(String.format(getString(R.string.text_purchase_product_tips),
                mProduct.getMinimumDay(),
                DateUtils.timestampToTimeStyle_4(
                        DateUtils.designationDayTimestamp(Integer.parseInt(mProduct.getMinimumDay())))
        )));
        mPurchaseProductAmountEdit.setHint(mProduct.getMinimumAmount() + "起购");

        // 选择可用资产百分比
        mPercentageAssets.setText("10%");

        // 协议
        mProtocolSelectedBox.setOnCheckedChangeListener((buttonView, isChecked) ->
                AndroidUtils.toggleButtonState(mPurchaseView, isChecked)
        );

        // 购买
        mPurchaseView.setOnClickListener(v ->
                requestPurchaseProduct(String.valueOf(mProduct.getId())));

        // 隐私协议
        mProtocolPrivacyView.setOnClickListener(v ->
                WebViewActivity.assetAgreement(v.getContext()));

        // 云端资产
        requestCloudAsset();
    }

    private void requestCloudAsset() {
        DataRepository.get().walletAssetAvailable(result -> {
            if (result.isSuccess()) {
                mAvailableAssetsText.setText("余额：" + result.getDataToString());

                // 购买全部
                mAllTextView.setOnClickListener(v ->
                        mPurchaseProductAmountEdit.setText(String.valueOf(result.getAmount())));
            }
        });
    }

    private void requestPurchaseProduct(String id) {
        String amount = mPurchaseProductAmountEdit.getText().toString();
        if (TextUtils.isEmpty(amount)) {
            Toasts.warning(R.string.message_please_enter_amount);
            return;
        }

        VerificationPasswordDialog
                .login()
                .setPositive(dialog -> {
                    if (LocalConfigStorage.get().getPassword().equals(dialog.getText())) {
                        DataRepository.get().generateFinancingOrders(id, amount, result -> {
                            if (result.isSuccess()) {
                                dialog.dismiss();
                                Toasts.success(R.string.message_generate_order_success);
                                EventBus.getDefault().post(new RequestHoldProductEvent());
                                EventBus.getDefault().post(new RequestUserAssetEvent());
                                EventBus.getDefault().post(new RequestWalletAssetEvent());
                                startActivity(new Intent(this, MainActivity.class));
                            } else {
                                dialog.setErrorMessage(result.getMsg());
                            }
                        });
                    } else {
                        dialog.setErrorMessage(getString(R.string.message_password_error));
                    }
                })
                .build(this)
                .show();
    }
}
